var crypto = require('crypto');
var config = require('../config');
/**
 * AES 对向加密解密类
 */
module.exports = {
	/* 接收aes加密字符串,返回json数据 */
	decrypt : function (text) {
		var decipher   = crypto.createDecipheriv('aes-128-ecb', config.aes_ecb_key, '');
		decipher.setAutoPadding(false);
		var deciphered = Buffer.concat([decipher.update(text, 'base64'), decipher.final()]);
		deciphered     = PKCS7Encoder.decode(deciphered);
		deciphered     = deciphered.toString();
		if (deciphered.substr(0, 1) == '{') {
			return JSON.parse(deciphered);
		} else {
			return false;
		}
	},
	/* 数组转换成json并加密 */
	encrypt : function (text) {
		text = JSON.stringify(text);
		var bufMsg  = new Buffer(text);
		var encoded = PKCS7Encoder.encode(bufMsg);
		var cipher  = crypto.createCipheriv('aes-128-ecb', config.aes_ecb_key, '');
		cipher.setAutoPadding(false);
		var cipheredMsg = Buffer.concat([cipher.update(encoded), cipher.final()]);
		return cipheredMsg.toString('base64');
	}
}

var PKCS7Encoder = {
	/* 删除补位 */
	decode : function (text) {
		var pad = text[text.length - 1];
		if (pad < 1 || pad > 16) {
			pad = 0;
		}
		return text.slice(0, text.length - pad);
	},
	/* 填充补位 */
	encode : function (text) {
		var blockSize = 16;
		var textLength = text.length;
		//计算需要填充的位数
		var amountToPad = blockSize - (textLength % blockSize);
		var result = new Buffer(amountToPad);
		result.fill(amountToPad);
		return Buffer.concat([text, result]);
	}
};